package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.hevs.samplewebapp.server.entities.InternalMessage;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.InternalMessageService;
import com.hevs.samplewebapp.server.service.UserService;

public class MessagingDeleteServlet extends SessionAuthHttpServlet{

	/**
	 * @author Arnaud Durand
	 */
	private static final long serialVersionUID = -8465617347860486644L;

	public static InternalMessageService internalMessageService;
	{
		internalMessageService = new InternalMessageService();
	};
	
	public static UserService userService;
	{
		userService = new UserService();
	};
	
	public MessagingDeleteServlet() {
		super(1);
	}
	
	@Override
	protected void doSecurePost(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		
		// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
		// globall
		BufferedReader reader = req.getReader();
		StringBuilder sb = new StringBuilder();
		String line = reader.readLine();
		while (line != null) {
			sb.append(line + "\n");
			line = reader.readLine();
		}
		reader.close();
		System.out.println(sb.toString());

		ObjectMapper mapper = ObjectMapperFactory.get();
		InternalMessage mail = mapper.readValue(sb.toString(), InternalMessage.class);

		// throw Error 400
		if (mail == null || mail.getKey() == null) {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}

		
		internalMessageService.removeMessage(mail);

	}
	
	
	
}
